package com.ruoyi.project.digital.util.gpt;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.project.digital.domain.Phrases;
import com.ruoyi.project.digital.util.Answer;
import com.ruoyi.project.digital.util.Choices;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class GptUtils {

    public static HttpPost httpPost;
    public static CloseableHttpClient httpClient;

    static {
        String openAiKey = "sk-VzVZ6IYyAHCG3I734e62CfCb3c154167B39b62316045B771"; //OpenAI??KEY?????????
        int connectTimeout = 600000; //??????
        int connectionRequestTimeout = 600000; //??????
        int socketTimeout = 600000; //socket??????
        HttpPost post = new HttpPost("https://api.opendevelop.tech/v1/chat/completions");
        post.addHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Bearer " + openAiKey);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectionRequestTimeout)
                .setSocketTimeout(socketTimeout)
                .build();
        post.setConfig(requestConfig);
        httpPost = post;
        try {
            httpClient = HttpClientBuilder.create()
                    .setSSLSocketFactory(getSslConnectionSocketFactory())
                    .build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

    public static String submit(String question) throws IOException {
        StringEntity stringEntity = new StringEntity(getRequestJson(question), getContentType());
        httpPost.setEntity(stringEntity);  //????????????
        CloseableHttpResponse response;
        response = httpClient.execute(httpPost); //?????????????
        return   printAnswer(response);
    }

    private static String printAnswer(CloseableHttpResponse response) throws IOException {
        String responseJson = EntityUtils.toString(response.getEntity());
        Answer answer = JSON.parseObject(responseJson, Answer.class);

        List<String> answerinfo = new ArrayList<>();
        List<Choices> choices = answer.getChoices();
        if(ObjectUtil.isNotNull(choices)){
            for (Choices choice : choices) {
                answerinfo.add(choice.getMessage().get(0).getRole());
                answerinfo.add(choice.getMessage().get(0).getContent());
            }

            System.out.println("role?" + answerinfo.get(0) + "?" + "content" + answerinfo.get(1)); //????
            return answerinfo.get(1);
        }else {
            return null;
        }

    }

    private static String getRequestJson(String question) {
        JSONObject messageContent = new JSONObject();
        messageContent.put("role", "user");
        messageContent.put("content", question);
        JSONArray messages = new JSONArray();
        messages.add(messageContent);
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "gpt-3.5-turbo");
        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);
        return JSONObject.toJSONString(requestBody, SerializerFeature.WriteMapNullValue);
    }

    public static void main(String[] args) throws IOException {
        List<Phrases> reslut=new ArrayList<>();
      String gptList=  submit("我今天心情糟糕，帮我生成几条聊天问候语，每条不超过8个字");
        String [] list=gptList.split("\\d+");
        for(String ss:list){
            if(!ss.equals("")&&ss.length()>=3){
                ss=ss.substring(1).trim();
                //  ss.replaceAll("\\d+","").replaceAll("。", "").trim();
                Phrases phrases=new Phrases();
                phrases.setUserId(11L);
                phrases.setName(ss);
                reslut.add(phrases);
                System.out.println(phrases.getName());
            }

        }
    }


    private static ContentType getContentType() {
        return ContentType.create("text/json", "UTF-8");
    }

    private static SSLConnectionSocketFactory getSslConnectionSocketFactory() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    }
}
